﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WaterRevenueMS.WebUI.Common;
using System.ComponentModel.Composition;
using WaterRevenueMS.Core.Service.BaseData;
using WaterRevenueMS.Core.Service.Customer;
using WaterRevenueMS.Core.Service.BasicSet;
using WaterRevenueMS.WebUI.Extension.Filters;
using WaterRevenueMS.Domain.ViewModels.Customer.Customer;
using WaterRevenueMS.Domain.Common.Models;
using WaterRevenueMS.Domain.ViewModels.BaseData.MeterBook;
using WaterRevenueMS.Componnent.Common;
using System.Linq.Expressions;
using WaterRevenueMS.Componnent.Entities.Customer;
using WaterRevenueMS.WebUI.Extension.MvcHelper;
using WaterRevenueMS.Domain.ViewModels.BasicSet.BankSet;
using System.Web.UI;
using WaterRevenueMS.Domain.ViewModels.BasicSet.AccountState;
namespace WaterRevenueMS.WebUI.Controllers
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class CustomerController : AdminController
    {
        [Import]
        public IMeterBookService MeterBookService { get; set; }

        [Import]
        public ICustomerService CustomerService { get; set; }

        [Import]
        public IBankSetService BankSetService { get; set; }

        [Import]
        private IRuleOfCodeService RuleOfCodeService { get; set; }

        [Import]
        private IAccountStateService AccountStateService { get; set; }
        
        [AdminLayout]
        public ActionResult Index()
        {
            var model = new CustomerModel();
            var meterBookDatas = MeterBookService.MeterBooks.Where(t => t.IsDeleted == false)
                .Select(t => new MeterBookModel
                {
                    id = t.Id,
                    Biao_CMC = t.Biao_CMC
                });
            foreach (var item in meterBookDatas)
            {
                model.Search.MeterBookItems.Add(new SelectListItem { Text = item.Biao_CMC, Value = item.id.ToString() });
            }
            return View(model);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult List(DataTableParameter param)
        {
            int total = CustomerService.Customers.Count(t => t.IsDeleted == false);

            var expr = BuildSearchCriteria();

            var filterResult = CustomerService.Customers.Where(expr).Select(t => new CustomerModel
            {
                Id = t.Id,
                Yong_HBH = t.Yong_HBH,
                Yong_HDZ = t.Yong_HZZ,
                Hu_ZXM = t.Hu_ZXM,
                Lian_XDH = t.Lian_XDH,
                Zhang_HYE = t.Zhang_HYE,
                MeterBookName = t.MeterBook != null ? t.MeterBook.Biao_CMC : "",
                OrderNo = t.OrderNo,


            }).OrderBy(t => t.OrderNo).Skip(param.iDisplayStart).Take(param.iDisplayLength).ToList();

            int sortId = param.iDisplayStart + 1;

            var result = from c in filterResult
                         select new[]
                        {
                            sortId++.ToString(), 
                            c.Yong_HBH,
                            c.Hu_ZXM,
                            c.Lian_XDH,
                            c.Zhang_HYE.ToString(),
                            c.MeterBookName,
                            c.Yong_HDZ,
                            c.Id.ToString()
                        };

            return Json(new
            {
                sEcho = param.sEcho,
                iDisplayStart = param.iDisplayStart,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Create()
        {
            var model = new CustomerModel();
            InitModuleSet(model);
            InitCustomerCode(model);
            return PartialView(model);
        }

        [HttpPost]
        [AdminOperateLog]
        public ActionResult Create(CustomerModel model)
        {
            if (ModelState.IsValid)
            {
                
                OperationResult result = CustomerService.Insert(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    InitModuleSet(model);
                    InitCustomerCode(model);
                    return PartialView(model);
                }
            }
            else
            {
                InitModuleSet(model);
                InitCustomerCode(model);
                return PartialView(model);
            }
        }

        public ActionResult Edit(int Id)
        {
            var model = new CustomerModel();
            var entity = CustomerService.Customers.FirstOrDefault(t => t.Id == Id);
            if (null != entity)
            {
                model = new CustomerModel
                {
                    Yong_HBH = entity.Yong_HBH,
                    Yong_HDZ = entity.Yong_HZZ,
                    Zhu_FMJ = entity.Zhu_FMJ,
                    Hu_ZXM = entity.Hu_ZXM,
                    Hu_ZXB = entity.Hu_ZXB,
                    Lian_XDH = entity.Lian_XDH,
                    Shen_FZH = entity.Shen_FZH,
                    Jia_TCY = entity.Jia_TCY,
                    Yin_HSZ_No = entity.Yin_HSZ_No,
                    Biao_CSZ_No = entity.Biao_CSZ_No,
                    Yin_HZH = entity.Yin_HZH,
                    Zhang_HYE = entity.Zhang_HYE,
                    Zhang_HZT = entity.Zhang_HZT,
                    Yu_EBJX = entity.Yu_EBJX,
                    Yu_ETYX = entity.Yu_ETYX,
                    OrderNo = entity.OrderNo
                };
                InitModuleSet(model);
                InitCustomerCode(model);
            }
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult Edit(CustomerModel model)
        {
            if (ModelState.IsValid)
            {
                
                OperationResult result = CustomerService.Update(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    InitModuleSet(model);
                    return PartialView(model);
                }

            }
            else
            {
                InitModuleSet(model);
                return PartialView(model);
            }
        }


        public ActionResult Delete(int Id)
        {
            OperationResult result = CustomerService.Delete(Id);
            return Json(result);
        }


        private Expression<Func<Customer, Boolean>> BuildSearchCriteria()
        {
            DynamicLambda<Customer> bulider = new DynamicLambda<Customer>();
            Expression<Func<Customer, Boolean>> expr = null;
            if (!string.IsNullOrEmpty(Request["Hu_ZXM"]))
            {
                var data = Request["Hu_ZXM"].Trim();
                Expression<Func<Customer, Boolean>> tmp = t => t.Hu_ZXM.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Yong_HBH"]))
            {
                var data = Request["Yong_HBH"].Trim();
                Expression<Func<Customer, Boolean>> tmp = t => t.Yong_HBH.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Lian_XDH"]))
            {
                var data = Request["Lian_XDH"].Trim();
                Expression<Func<Customer, Boolean>> tmp = t => t.Lian_XDH.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Shen_FZH"]))
            {
                var data = Request["Shen_FZH"].Trim();
                Expression<Func<Customer, Boolean>> tmp = t => t.Shen_FZH.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Biao_CSZ_No"]) && Request["Biao_CSZ_No"] != "0")
            {
                var data = Convert.ToInt32(Request["Biao_CSZ_No"]);
                Expression<Func<Customer, Boolean>> tmp = t => (t.Biao_CSZ_No == data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            Expression<Func<Customer, Boolean>> tmpSolid = t => t.IsDeleted == false;
            expr = bulider.BuildQueryAnd(expr, tmpSolid);

            return expr;
        }

        private void InitModuleSet(CustomerModel model)
        {
            //表册初始化
            var meterBookDatas = MeterBookService.MeterBooks.Where(t => t.IsDeleted == false)
                .Select(t => new MeterBookModel
                {
                    id = t.Id,
                    Biao_CMC = t.Biao_CMC
                });
            foreach (var item in meterBookDatas)
            {
                model.MeterBookItems.Add(new SelectListItem { Text = item.Biao_CMC, Value = item.id.ToString() });
            }
            //开户银行初始化
            var bankDatas = BankSetService.BankSets.Where(t => t.IsDeleted == false)
                .Select(t => new BankSetModel
                {
                    Id = t.Id,
                    Yin_HMC = t.Yin_HMC
                });
            foreach (var item in bankDatas)
            {
                model.BankItems.Add(new SelectListItem { Text = item.Yin_HMC, Value = item.Id.ToString() });
            }

            var accountStateDatas = AccountStateService.AccountStates.Where(t => t.IsDeleted == false)
                .Select(t => new AccountStateModel {
                     Id=t.Id,
                     Zhang_HZT=t.Zhang_HZT
                });
            foreach (var item in accountStateDatas)
            {
                model.AccountStateItems.Add(new SelectListItem {Text=item.Zhang_HZT,Value=item.Id.ToString() });
            }
        }

        private void InitCustomerCode(CustomerModel model)
        {
            var codeRule = RuleOfCodeService.RuleOfCodes.FirstOrDefault(t => t.Bian_MDX == 1);
            if (codeRule != null)
            {
                model.RuleOfCode = codeRule.Bian_MGZDY;
            }
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
        public JsonResult IsUnique_Available(string Yong_HBH)
        {
            if (!string.IsNullOrEmpty(Yong_HBH))
            {
                var entity = CustomerService.Customers.FirstOrDefault(t => t.Yong_HBH == Yong_HBH);
                if (entity != null)
                {
                    //string message = "该用户编号已经存在";
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }

    }
}

